package com.cloudkinto.inteceptors;

import com.cloudkinto.common.annotations.UserSessionRequired;
import com.cloudkinto.common.common.DateUtils;
import com.cloudkinto.session.UserSession;
import com.cloudkinto.session.UserSessionManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;


/**
 * @author zhangyy
 * @date 2020 -5-9
 */
@Component
public class UserSessionProcessor extends HandlerInterceptorAdapter {

    private static Logger logger = LoggerFactory.getLogger(UserSessionProcessor.class);

    @Value("${gbc.server.http-session}")
    private boolean httpRequestSession;

    @Value("${server.servlet.session.timeout}")
    private int sessionMaxTime;

    @Autowired
    private UserSessionManager userSessionManager;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (httpRequestSession) {//如果开启用户权限验证
            if (handler instanceof HandlerMethod) {
                HandlerMethod method = (HandlerMethod) handler;
                if (method.getMethod().isAnnotationPresent(UserSessionRequired.class)) {//如果请求的方法有该注解标注
                    // 将当前请求写入本地线程中
                    RequestHolder.setRequestLocal(request);
                    RequestHolder.setResponseLocal(response);
                    UserSession userSession = userSessionManager.getSession(request);
                    if (request.getSession().getAttribute(UserSession.SESSION_ID_KEY) == null) {
                        request.getSession().setAttribute(UserSession.SESSION_ID_KEY, userSession);
                    }
                    if ("com.cloudkinto.controller.user.UserController".equals(method.getBeanType().getName()) && "logout".equals(method.getMethod().getName())) {
                        //退出接口
                        redisTemplate.opsForZSet().remove("oms-user-online", userSession.getUserId());
                    }
                    else {
                        //用户签到记录
                        redisTemplate.opsForValue().setBit("oms-user-sign-"+ DateUtils.dateFormatToString(new Date(), "yyyyMMdd"), userSession.getUserId(), true);
                        //用户在线记录
                        redisTemplate.opsForZSet().add("oms-user-online", userSession.getUserId(), new Date().getTime());
                    }
                }
            }
        }
        response.setHeader("Set-Cookie", "key=value; HttpOnly; SameSite=None; Secure");
        return super.preHandle(request, response, handler);
    }


    public UserSessionManager getUserSessionManager() {
        return userSessionManager;
    }

    public void setUserSessionManager(UserSessionManager userSessionManager) {
        this.userSessionManager = userSessionManager;
    }

    public boolean isHttpRequestSession() {
        return httpRequestSession;
    }

    public void setHttpRequestSession(boolean httpRequestSession) {
        this.httpRequestSession = httpRequestSession;
    }

}
